package com.example.demo.demo.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 公平锁 & 非公平锁
 *      非公平锁性能高于公平锁性能。首先，在恢复一个被挂起的线程与该线程真正运行之间存在着严重的延迟（切换线程上下文耗时）。
 *      而且，非公平锁能更充分的利用cpu的时间片，尽量的减少cpu空闲的状态时间。
 * @author: htc
 * @date: Created in 18:24 2018/10/25.
 */
public class FairLockAndUnFairLock {
    /**
     * 公平锁
     */
    private ReentrantLock fairLock = new ReentrantLock(true);
    /**
     * 非公平锁
     */
    private ReentrantLock nonFairLock = new ReentrantLock(false);

    public void fair() {
        try {
            fairLock.lock();
            System.out.println(Thread.currentThread().getName() + "获得了锁");
        } finally {
            fairLock.unlock();
        }
    }

    public void unFair() {
        try {
            nonFairLock.lock();
            System.out.println(Thread.currentThread().getName() + "获得了锁");
        } finally {
            nonFairLock.unlock();
        }
    }


    public static void main(String[] args) {
        FairLockAndUnFairLock lock = new FairLockAndUnFairLock();
        Runnable runnable = () -> {
            System.out.println(Thread.currentThread().getName() + "启动");
//            lock.fair();
            lock.unFair();
        };
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(runnable);
        }
        for (int i = 0; i < 10; i++) {
            threads[i].start();
        }
    }
}
